package com.jws.battleship;

import java.util.ArrayList;
import java.util.zip.DataFormatException;

public class Ship 
{
	public final static int TYPE_NORMAL = 0;
	public final static int TYPE_BIG = 1;
	public final static int TYPE_SMALL = 2;
	
	private Coordinate mStartPosition;
	private Coordinate mDirection;
	private int mType;
	
	public Ship()
	{
		
	}
	
	public Ship(String ship)
	{
		String[] values = ship.split(";");
		
		mType = Integer.parseInt(values[0]);
		mStartPosition = new Coordinate(values[1]);
		mDirection = new Coordinate(values[2]);
	}

	

	public Coordinate getStartPosition() {
		return mStartPosition;
	}

	public void setStartPosition(Coordinate startPosition) {
		this.mStartPosition = startPosition;
	}

	public Coordinate getDirection() {
		return mDirection;
	}
	
	public int getDirectionDegree() 
	{
		Integer degree = null;
		
		switch (mDirection.x) 
		{
		case 1:
			switch (mDirection.y) 
			{
			case 1:
				degree = 45;
				break;
				
			case -1:
				degree = 315;
				break;
				
			case 0:
				degree = 0;
				break;
			}
			break;
			
		case -1:
			switch (mDirection.y) 
			{
			case 1:
				degree = 135;
				break;
				
			case -1:
				degree = 225;
				break;
				
			case 0:
				degree = 180;
				break;
			}
			break;
			
		case 0:
			switch (mDirection.y) 
			{
			case 1:
				degree = 90;
				break;
				
			case -1:
				degree = 270;
				break;
			}
			break;
		}
		
		return degree;
	}

	public void setDirection(Coordinate direction) throws DataFormatException 
	{
		if(direction.x >= -1 && direction.x <= 1 && direction.y >= -1 && direction.y <= 1)
			this.mDirection = direction;
		else
			throw new DataFormatException();
	}
	
	public int getType() {
		return mType;
	}

	public void setType(int type) throws DataFormatException
	{
		if(type >= 0 && type <= 2)
			this.mType = type;
		
		else 
			throw new DataFormatException();
	}

	@Override
	public String toString() 
	{		
		StringBuilder sb = new StringBuilder();
		
		sb.append(mType);
		sb.append(";");
		sb.append(mStartPosition.toString());
		sb.append(";");
		sb.append(mDirection.toString());
		
		return sb.toString();
	}
	
	public static String shipListToString(ArrayList<Ship> ships)
	{
		StringBuilder sb = new StringBuilder();
		
		for (Ship ship: ships) 
		{			
			sb.append(ship.toString());
			sb.append(":");
		}
		
		sb.deleteCharAt(sb.length()-1);
		
		return sb.toString();
	}
	
	public static ArrayList<Ship> stringToShipList(String string)
	{
		ArrayList<Ship> list = new ArrayList<Ship>();
		
		for (String shipString : string.split(":")) 
		{			
			list.add(new Ship(shipString));
		}
		
		return list;
	}
}